package com.git.hui.yinshua.biz.banner.service;

import com.git.hui.yinshua.api.model.ListRsp;
import com.git.hui.yinshua.api.model.banner.BannerTabEnum;
import com.git.hui.yinshua.biz.banner.dao.entity.BannerEntity;
import com.git.hui.yinshua.biz.banner.dao.repository.BannerRepository;
import com.git.hui.yinshua.biz.banner.service.convert.BannerConvert;
import com.git.hui.yinshua.biz.rest.models.banner.req.BannerReq;
import com.git.hui.yinshua.biz.rest.models.banner.res.BannerDto;
import com.git.hui.yinshua.biz.util.ImgUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author YiHui
 * @date 2024/6/17
 */
@Service
public class BannerService {
    @Autowired
    private BannerRepository bannerRepository;

    public BannerDto add(BannerReq req) {
        if (StringUtils.isNotBlank(req.getImg()) && req.getImgColor() == null) {
            req.setImgColor(ImgUtil.getImgBgColor(req.getImg()));
        }
        BannerEntity banner = bannerRepository.saveBanner(req);
        return BannerConvert.toBanner(banner);
    }

    public boolean update(BannerReq req) {
        if (StringUtils.isNotBlank(req.getImg()) && req.getImgColor() == null) {
            req.setImgColor(ImgUtil.getImgBgColor(req.getImg()));
        }
        return bannerRepository.updateBanner(req);
    }

    public boolean online(Integer bannerId, boolean online) {
        return bannerRepository.online(bannerId, online);
    }

    public boolean delete(Integer bannerId) {
        return bannerRepository.deleteBanner(bannerId);
    }

    public ListRsp<BannerDto> list(BannerReq req) {
        req.autoInitReq();
        List<BannerEntity> list = bannerRepository.bannerList(req);
        List<BannerDto> ans = BannerConvert.batchToBanners(list);
        ListRsp<BannerDto> res = ListRsp.newRsp(ans, req.getPage(), req.getSize());
        if (req.getPage() == 1) {
            int cnt = bannerRepository.count(req);
            res.setTotal(cnt);
        }
        return res;
    }


    // ---------------------------- 下面是给前台app使用的service

    @Cacheable(cacheNames = "ys", key = "'banner' + #tab", cacheManager = "caffeineCacheManager")
    public List<BannerDto> queryForTab(BannerTabEnum tab) {
        List<BannerEntity> list = bannerRepository.queryForTab(tab.getTab());
        return BannerConvert.batchToBanners(list);
    }
}
